package com.cmc.cloud.cmclink.doc.framework.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.fastjson.JSON;
import com.cmc.cloud.cmclink.doc.vo.hscodevo.HsCodeImportVo;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * excel 导入监听器
 *
 * @author 周贤
 */
@Slf4j
public class HsCodeExcelListener extends AnalysisEventListener<HsCodeImportVo> {

    List<HsCodeImportVo> res;

    public HsCodeExcelListener(List<HsCodeImportVo> res) {
        this.res = res;
    }

    /**
     * 解析异常调用
     *
     * @param exception
     * @param context
     * @throws Exception
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        log.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
        }
    }

    /**
     * 解析表头
     *
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {

    }

    /**
     * 解析每行数据调用
     *
     * @param data
     * @param context
     */
    @Override
    public void invoke(HsCodeImportVo data, AnalysisContext context) {
        ReadRowHolder readRowHolder = context.readRowHolder();
        Integer rowIndex = readRowHolder.getRowIndex();
        data.setRowNumber(rowIndex + 1);
        res.add(data);
    }


    @Override
    public void extra(CellExtra extra, AnalysisContext context) {

    }

    /**
     * 所有数据解析完成后调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成！");
        log.info("解析数据:{}", JSON.toJSONString(res));
    }
}